var id=GetQueryString('id')
getData()
var dohtml=''
var imgs=[]
var hasstep=[]
function getData(){
    var index
    var ajaxData={
        url:'task_manage/taskdetail',
        fromwho:'manage',
        sendData:{
           guid: id
        }
    }
    getAjax(ajaxData,function(data){
        if(data.code==200){
            var curData=data.data
            var tplData={v:curData}
            //详情
            var html= template('tpl-taskDetail', tplData);
            $('.detail').html(html)
            //任务步骤
            var html2= template('tpl-taskDo', tplData);
            dohtml=html2
            $('.do').prepend(html2)
            $(':input').labelauty();
            inituploder()
            //已完成任务
            var ajaxData2={
                url:'task_manage/finishlist',
                fromwho:'manage',
                sendData:{p:'',id:curData.guid}
            }
            getAjax(ajaxData2,function(data){
                console.log(data)
                if(data.code==200){
                    var finishData=data.data
                    var tplData={curData:finishData}
                    var html3= template('tpl-taskDone', tplData);
                    $('.done').prepend(html3)
                    $.each(finishData,function(k,v){
                        var arr=v.step.toString().split(',')
                        hasstep=$.unique($.merge(hasstep,arr));
                    })
                    $('input[name="task_step"]').each(function(k,v){
                        var index=(k+1).toString()
                        if($.inArray(index,hasstep)!=-1){
                            $(v).attr('checked',true)
                            $(v).attr('disabled',true)
                        }
                    })
                }
            })
        }
    },function(){index=layer.open({type: 2});},function(){layer.close(index);})
}
$('.mui-content').on('tap','.popuptask',function(){
//  console.log(dohtml)
    var fid=$(this).data('id')
    var ajaxData={
        url:'task_manage/finishtaskdetail',
        fromwho:'manage',
        sendData:{guid:fid}
    }
    getAjax(ajaxData,function(data){
        var showhtml=dohtml
        if(data.code!=200){
            return false;
        }
        var curData=data.data
        var step=curData.step.split(',')
//      if(curData.check_status=='WAIT'){
//          showhtml+=`<span class="editTask">提交修改</span>`
//      }
        layer.open({
                type: 1
                ,content: showhtml
                ,anim: 'up'
                ,style: 'position:fixed; bottom:0; left:0; width: 100%; max-height: 80vh;border:none;background-color: #efeff4'
                ,success:function(layero){
                    $(layero).find('textarea').val(curData.finish_des);
                    $(layero).find(':input').each(function(k,v){
                        if(curData.step.indexOf(k+1)!=-1){
                            $(v).attr('checked',true)
                        }
                    })
                    $(layero).find('#mainadd').attr('id','popupadd')
                    $(layero).find(':input').labelauty();
                    $(layero).find(':input').attr('disabled',true)
                    $('.filebtns').remove()
                    if(curData.imgs&&curData.imgs.length>0){
                        var imghtml=''
                        $.each(curData.imgs, function(k,v) {
                            imghtml+=`<img style="width:60px;height:60px;margin:5px" data-id="${v.id}" src=${catchurl(v.accessory_new_name)}><img>`
                        });
                        $(layero).find('.uploader-list').html(imghtml)
                    }
                    
//                   if(curData.check_status!='WAIT'){
//                      $('.uploadFiles').remove()
//                      $(layero).find(':input').attr('readonly',true)
//                  }
                }
            });
    },function(){index=layer.open({type: 2});},function(){layer.close(index);})
})
//保存save
$('.save').on('click',function(){
    var steps=[] 
    var imgids=[]
    $('input[name="task_step"]:checked').each(function(k,v){
        steps.push(v.value)
    })
    $('.file-item').each(function(k,v){
        imgids.push($(v).data('id'))
    })
    imgidsString=imgids.join(',')
//  console.log(imgidsString)
//  Array.from(new Set(hasstep))
    var task_memo=$('.memo').val()
    if(steps.length==0){
        mui.toast('请选择当前完成步骤')
        return false
    }
    if(!task_memo){
        mui.toast('请输入完成情况')
        return false
    }
    var fstatus=hasstep.length+steps.length
    var ajaxData={
        url:'task_manage/finishtask',
        fromwho:'manage',
        sendData:{
            task_guid:id,
            finish_step:steps.join(','),
            finish_id:'',
            img:imgidsString,
            tag:'add',
            task_memo:task_memo,
            fstatus:fstatus
        }
    }
//  console.log(ajaxData)
    upData(ajaxData)
    
})
//提交资料
function upData(ajaxData){
    var index
    upAjax(ajaxData,function(data){
        if(data.code==200){
            layer.open({
                content: '提交成功'
                ,skin: 'msg'
                ,time: 1//2秒后自动关闭
            });
            setTimeout(function(){
                location.reload()
            },1000)
        }else{
            layer.open({
                content: '提交失败'
                ,skin: 'msg'
                ,time: 1//2秒后自动关闭
            });
        }
    },function(){index=layer.open({type: 2,content: '提交中'});},function(){layer.close(index);})
}
//上传图片
function inituploder(element,listelement,uploadbtn){
    var element=element ? element : '#filePicker'
    var listelement=listelement ? listelement : '.uploader-list'
    var uploadbtn=uploadbtn ? uploadbtn : '.fileUp'
    var state = 'pending'; // 上传文件初始化  
    var uploader = WebUploader.create({
        auto: true,
        server: httpurl('task_manage/uploadissueimgapi','manage'),
        pick: element,
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/*'
        }
    });
    $(uploadbtn).on('click', function() {  
        if (state === 'uploading') {  
            uploader.stop();  
        } else {  
            uploader.upload();  
        }  
    });  
    uploader.on( 'fileQueued', function( file ) {
        var $li = $(
            '<div id="' + file.id + '" class="file-item thumbnail">' +
                '<img>' +
            '</div>'
            ),
        
        $img = $li.find('img');
        $(listelement).append( $li );
        // 创建缩略图
        uploader.makeThumb( file, function( error, src ) {
            if ( error ) {
                $img.replaceWith('<span>不能预览</span>');
                return;
            }
            $img.attr( 'src', src );
        }, 70, 70 );
    });
    uploader.on( 'filesQueued', function( file ) {
        //删除文件
        $('.file-item').on('click',function() {
            if($(this).hasClass('upload-state-done')!=-1){
                var id=$(this).data('id')
            }
            uploader.removeFile(this.id);
            $(this).remove()
        })
    });
    uploader.on( 'uploadProgress', function( file, percentage ) {
        var $li = $( '#'+file.id ),
            $percent = $li.find('.progress span');
        // 避免重复创建
        if ( !$percent.length ) {
            $percent = $('<p class="progress"><span style="background: #2B7DC4;height: 2px;display: inline-block;position: absolute;"></span></p>')
                    .appendTo( $li )
                    .find('span');
        }
        $percent.css( 'width', percentage * 100 + '%' );
    });
    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    uploader.on( 'uploadSuccess', function( file,response ) {
        $( '#'+file.id ).attr('data-id',response);
        $( '#'+file.id ).addClass('upload-state-done');
    });
    // 文件上传失败，显示上传出错。
    uploader.on( 'uploadError', function( file ) {
        var $li = $( '#'+file.id ),
            $error = $li.find('div.error');
    
        // 避免重复创建
        if ( !$error.length ) {
            $error = $('<div class="error"></div>').appendTo( $li );
        }
    
        $error.text('上传失败');
    });
    
    // 完成上传完了，成功或者失败，先删除进度条。
    uploader.on( 'uploadComplete', function( file ) {
        $( '#'+file.id ).find('.progress').remove();
    });
}
